package com.stars.empoly.vmodel

import android.app.Activity
import android.app.Application
import android.text.TextUtils
import androidx.databinding.Bindable
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.hwangjr.rxbus.RxBus
import com.stars.empoly.BR
import com.stars.empoly.activity.ChoseBaiDuActivity
import com.stars.empoly.config.ConfigRx
import com.stars.empoly.config.MIntentAction
import com.stars.empoly.model.User
import com.stars.empoly.utils.ChosePhotoUtils
import com.stars.empoly.utils.net.NetEngine
import com.trailer.base.base.BRepository
import com.trailer.base.base.BViewModel
import com.trailer.base.utils.UiSwitch
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.coroutines.launch

class PersonalInfoVModel(application: Application) : BViewModel<BRepository>(application) {

    val user: MutableLiveData<User?> = MutableLiveData(User.get())
    var headImg: MutableLiveData<String> = MutableLiveData()
    var avatar:String?=null


    fun setInitData() {


    }

    @Bindable
    open var name: String? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.name)
        }

    fun choseImg() {

        //选择照片
        ChosePhotoUtils.getChosePhoto(view()!!.context(), 1)

    }

    fun toChoseAddress(){







        AndPermission.with(repository().context)
            .runtime()
            .permission(
                Permission.WRITE_EXTERNAL_STORAGE,
                Permission.READ_EXTERNAL_STORAGE,
                Permission.ACCESS_COARSE_LOCATION,
                Permission.ACCESS_FINE_LOCATION
            )
            .onGranted { data ->

                UiSwitch.singleRes(repository().context as Activity,
                    ChoseBaiDuActivity::class.java, MIntentAction.REQUEST_CODE_ONE)


            }
            .start()
        AndPermission.with(repository().context)
            .runtime()
            .permission(
                Permission.WRITE_EXTERNAL_STORAGE,
                Permission.READ_EXTERNAL_STORAGE,
                Permission.ACCESS_COARSE_LOCATION,
                Permission.ACCESS_FINE_LOCATION
            )
            .onGranted { data ->

                UiSwitch.singleRes(repository().context as Activity,
                    ChoseBaiDuActivity::class.java, MIntentAction.REQUEST_CODE_ONE)


            }
            .start()



    }

    fun toSubmit(){
        if(TextUtils.isEmpty(name)){
            toast("请输入用户名")
            return
        }

        viewModelScope.launch {
           var it= repository().lreq { NetEngine.service.profile(name,avatar) }
            if(it.ok(true)){

                RxBus.get().post(ConfigRx.REFRESH_USER, "")
                (repository().context as Activity).finish()
            }
        }


    }




}



